# 构建用户画像
from collections import OrderedDict
import io
import csv
import json
import sys

from py2neo import Graph
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from py2neo import Graph
import redis
from bulid_distance import city_similarity, read_cities_data, get_ex_cities

sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

citycsv = open('data/job.csv', 'r', encoding="utf-8")
cityreader = csv.reader(citycsv)
jobData = list(cityreader)

# 连接到 Redis 服务器
redis_client = redis.StrictRedis(host='8.140.243.61', port=6210, db=0)


def get_recommendations_from_cache(userName):
    # 构建带有用户标识的缓存键
    cache_key = f'user:{userName}:job_results'
    # 从 Redis 获取数据
    job_results = redis_client.get(cache_key)
    if job_results:
        return job_results.decode('utf-8')  # 返回缓存数据

    return None  # 返回空表示缓存不存在或已过期


def store_jobs_to_redis():
    graph = Graph("http://localhost:7474", auth=("neo4j", "Xiyou666"), name="neo4j")
    job_result = []
    for i in range(1, len(jobData)):
        results = []
        query = '''
                MATCH (j:job {id: $jobId})
                RETURN j
                '''
        # 执行查询并传入参数
        result = graph.run(query, jobId=jobData[i][0]).data()
        job_result.extend(result)
    all_dict = []
    for result in job_result:
        job_dict = {
            "id": result['j']['id'],
            "company": result['j']['company'],
            "title": result['j']['name'],
            "salary": result['j']['salary'],
            "education": result['j']['education'],
            "description": result['j']['description'],
            "hiring_manager": result['j']['hiring_manager'],
            "last_active": result['j']['last_active'],
            "address": result['j']['address'],
            "link": result['j']['link'],
        }
        all_dict.append(job_dict)
    json_str = json.dumps(all_dict, ensure_ascii=False)
    # 将数据存储到 Redis 中，设置过期时间为 3600 秒（1 小时）
    redis_client.set('All', json_str)
    redis_client.expire('All', 3600)
    return json_str


def get_jobs_from_redis(keys):
    results = redis_client.get(keys)
    if results:
        return results.decode('utf-8')  # 返回缓存数据

    return None  # 返回空表示缓存不存在或已过期


def get_all_job():
    AllJob = get_jobs_from_redis('All')
    if AllJob:
        return AllJob  # 直接返回缓存中的推荐数据
    else:
        AllJob = store_jobs_to_redis()
        return AllJob


def job_search(keys):
    graph = Graph("http://localhost:7474", auth=("neo4j", "Xiyou666"), name="neo4j")
    job_result = []
    query = '''
       MATCH (j:job)
       WHERE toLower(j.name) =~ "(?i).*" + toLower($name) + ".*"
       RETURN j
       LIMIT 20
    '''
    results = graph.run(query, name=keys).data()
    job_result.extend(results)
    search_dict = []
    for result in job_result:
        job_dict = {
            "id": result['j']['id'],
            "company": result['j']['company'],
            "title": result['j']['name'],
            "salary": result['j']['salary'],
            "education": result['j']['education'],
            "description": result['j']['description'],
            "hiring_manager": result['j']['hiring_manager'],
            "last_active": result['j']['last_active'],
            "address": result['j']['address'],
            "link": result['j']['link'],
        }
        search_dict.append(job_dict)
    json_str = json.dumps(search_dict, ensure_ascii=False)
    return json_str


if __name__ == '__main__':
    argument = ''
    # 打印传递的参数
    if len(sys.argv) > 1:
        argument = sys.argv[1]
    json = job_search(argument)
    # json = job_search(argument)
    print(json)

    # json = get_all_job()
    # print(json)
